package code.whmmm.util.simple.calculate;

import code.whmmm.util.simple.Vw;
import code.whmmm.util.simple.decimal.DecimalFormatter;

import java.math.BigDecimal;

/**
 * <p><b>
 *
 * </b></p>
 * <br/>
 * 创建时间: 2019/11/30 14:17
 *
 * @author Zero
 */
public class BigDecimalCalc implements CalcInterface<BigDecimalCalc> {


    private BigDecimal result;

    public BigDecimalCalc() {
        this(0);
    }

    public BigDecimalCalc(Object num) {
        if (num == null) {
            num = 0;
        }
        result = new BigDecimal(Vw.string(num));
    }


    public static BigDecimalCalc create() {
        return create(0);
    }

    public static BigDecimalCalc create(Object num) {
        if (num == null) {
            num = 0;
        }
        return new BigDecimalCalc(Vw.string(num));
    }

    @Override
    public BigDecimalCalc add(Object... nums) {
        for (Object num : nums) {
            if (num == null) {
                num = 0;
            }
            this.result = result.add(new BigDecimal(Vw.string(num)));
        }
        return this;
    }

    @Override
    public BigDecimalCalc minus(Object... nums) {
        for (Object num : nums) {
            if (num == null) {
                num = 0;
            }
            this.result = result.subtract(new BigDecimal(Vw.string(num)));
        }
        return this;
    }

    @Override
    public BigDecimalCalc multi(Object... nums) {
        for (Object num : nums) {
            if (num == null) {
                num = 0;
            }
            this.result = result.multiply(new BigDecimal(Vw.string(num)));
        }
        return this;
    }

    /**
     * 除法，保留 三位小数 ！ 四舍五入
     *
     * @param nums
     * @return
     */
    @Override
    public BigDecimalCalc divide(Object... nums) {
        for (Object num : nums) {
            if (num == null) {
                num = 1;
            }
            this.result = result.divide(new BigDecimal(Vw.string(num)), 3, BigDecimal.ROUND_HALF_UP);
        }
        return this;
    }

    /**
     * 四舍五入 ,保留两位小数
     *
     * @return
     */
    public String getFormatNum() {
        return DecimalFormatter.stdFormat(result);
    }

    public String getFormatNum(String pattern){
        return new java.text.DecimalFormat(pattern).format(result);
    }

    public String getFormatNum(java.text.DecimalFormat format){
        return format.format(result);
    }

    /**
     * 获取内部的 {@link BigDecimal} 对象
     *
     * @return
     */
    public BigDecimal get() {
        return result;
    }
}
